'use strict';

var _createClass = function () { function defineProperties(target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; descriptor.configurable = true; if ("value" in descriptor) descriptor.writable = true; Object.defineProperty(target, descriptor.key, descriptor); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; }();

function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } }

/**
 * 歌词滚动
 * author: lanqin
 * zhenjiang.szj@alibaba-inc.com
 * since 2016.05.30
 * modified by yueshui at 2017.3.6
 */

var LyricView = function () {
  function LyricView(container, dataStr) {
    _classCallCheck(this, LyricView);

    container = container || document.body;
    this.con = container;
    this.line = 0;
    this.showData = {};
    this.formatShowData = {};
    this.hasLyric = false;
    if (dataStr) {
      this.parseData(dataStr);
      this.render(container, this.formatShowData);
      this.reset();
    }
  }

  /**
  * 解析 lrc 字符串
  */


  _createClass(LyricView, [{
    key: 'parseData',
    value: function parseData(dataStr) {
      var dataArr = dataStr.split('\n');
      for (var i = 0, len = dataArr.length; i < len; i++) {
        var lrcClause = dataArr[i].replace(/\[\d*:\d*((\.|\:)\d*)*\]/g, '');
        var timeArr = dataArr[i].match(/\[\d*:\d*((\.|\:)\d*)*\]/g);
        if (timeArr) {
          for (var j = 0, lenn = timeArr.length; j < lenn; j++) {
            var min = Math.floor(timeArr[j].match(/\[\d*/i).toString().slice(1));
            var sec = Math.floor(timeArr[j].match(/\:\d*/i).toString().slice(1));
            var time = min * 60 + sec;
            this.showData[time] = lrcClause.replace(/(^\s*)|(\s*$)/g, '');
          }
        }
      }
      for (var index in this.showData) {
        if (this.showData[index] != '' && index != '0') {
          this.formatShowData[index] = this.showData[index];
        }
      }
    }

    /**
    * 渲染歌词区域
    */

  }, {
    key: 'render',
    value: function render(con, data) {
      var i = 0;
      var html = [];
      var indexArr = [];

      // blitz 内核需要对键值先进行排序，chrome不需要
      function sortNumber(a, b) {
        return a - b;
      }
      for (var index in data) {
        indexArr.push(index);
      }
      indexArr.sort(sortNumber);
      this.indexArr = indexArr;
      var len = indexArr.length;
      if (len != 0) {
        this.hasLyric = true;
        this.lastLine = -2;
      }
      var j = 0;
      for (i = 0; i < len; i++) {
        var _index = indexArr[j];
        var lrcClause = data[_index];
        // 处理英文歌词
        if (escape(lrcClause).indexOf("%u") < 0) {
          // 处理英文换行
          if (lrcClause.length > 40) {
            var tempArr = lrcClause.split(' ');
            var _len = tempArr.length;
            var clause1 = tempArr.slice(0, _len / 2).join(' ');
            var clause2 = tempArr.slice(_len / 2, _len).join(' ');
            html[j] = '<p class="song-clause" id="song-line' + j + '">' + clause1 + '</p>';
            html[j + 1] = '<p class="song-clause" id="song-line' + (j + 1) + '">' + clause2 + '</p>';
            var nextIndex = indexArr[j + 1] || _index;
            var insertIndex = (+_index + +nextIndex) / 2;
            indexArr.splice(j + 1, 0, +insertIndex); // 插入一行, 播放时间点为insertIndex
            j += 2;
          } else {
            html[j] = '<p class="song-clause" id="song-line' + j + '">' + lrcClause + '</p>';
            j++;
          }
        } else {
          // 处理非英文歌词
          // 中文换行
          if (lrcClause.length > 20) {
            var _len2 = lrcClause.length;
            var _clause = lrcClause.slice(0, _len2 / 2);
            var _clause2 = lrcClause.slice(_len2 / 2, _len2);

            html[j] = '<p class="song-clause" id="song-line' + j + '">' + _clause + '</p>';
            html[j + 1] = '<p class="song-clause" id="song-line' + (j + 1) + '">' + _clause2 + '</p>';
            var _nextIndex = indexArr[j + 1] || _index;
            var _insertIndex = (+_index + +_nextIndex) / 2;
            indexArr.splice(j + 1, 0, +_insertIndex); // 插入一行, 播放时间点为insertIndex
            j += 2;
          } else {
            html[j] = '<p class="song-clause" id="song-line' + j + '">' + lrcClause + '</p>';
            j++;
          }
        }
      }
      this.line = j;
      var lrcHtml = html.join(' ');
      con.innerHTML = '<div class="lrc-container">' + lrcHtml + '</div>';
      this.calculate();
    }
  }, {
    key: 'calculate',
    value: function calculate() {
      this.wrapHeight = this.con.clientHeight;
      var line = document.querySelector('#song-line0');
      this.lineHeight = line.offsetHeight;
      var visibleLines = this.wrapHeight / this.lineHeight;
      this.scrollLines = Math.floor(visibleLines / 2);
    }
  }, {
    key: 'updateNoLyric',
    value: function updateNoLyric(msg) {
      this.hasLyric = false;
      var marginTop = this.con.clientHeight / 2 - 30;
      this.con.innerHTML = '<div class="lrc-container"><p class=\'song-clause\' id=\'song-line0\' style=\'margin-top: ' + marginTop + 'px\'>' + msg + '</p></div>';
    }

    /**
    * 刷新歌词内容
    */

  }, {
    key: 'refresh',
    value: function refresh(dataStr) {
      this.line = 0;
      this.showData = {};
      this.formatShowData = {};
      this.parseData(dataStr);
      this.render(this.con, this.formatShowData);
      this.reset();
    }
  }, {
    key: 'reset',
    value: function reset() {
      // 初始时偏移量需要确定
      document.querySelector('.lrc-container').transform = 'translateY(0px)';
    }
  }, {
    key: 'scrollLrc',
    value: function scrollLrc(time) {
      if (!this.hasLyric) {
        return;
      }
      var curTime = Math.round(time);
      var start = false;
      var i = 0;
      //console.log('---------------this.indexArr------: ' + JSON.stringify(this.indexArr));
      var len = this.indexArr.length;
      for (i = 0; i < len; i++) {
        var index = this.indexArr[i];
        if (index < curTime) {
          start = true;
        } else {
          break;
        }
      }
      var cLine = document.querySelector('#song-line' + (i - 1));
      if (cLine && start) {
        cLine.classList.add('current-line');
        // 处理一行拆成两行的情况，如果间隔为0.5秒，两行都变色，防止拆分出的第二行不变色
        if (+this.indexArr[i + 1] == +this.indexArr[i] + 0.5) {
          var nLine = document.querySelector('#song-line' + i);
          console.log('nline: ' + nLine.innerHTML);
          nLine && nLine.classList.add('current-line');
          this.scrollLrcLine(i - 1, true);
        } else {
          this.scrollLrcLine(i - 1);
        }
      }
    }
  }, {
    key: 'scrollLrcLine',
    value: function scrollLrcLine(lineNum, nohide) {
      //let stride = 75; // 歌词滚动距离
      if (this.lastLine == lineNum) {
        return;
      }
      this.lastLine = lineNum;
      var preline = void 0;
      lineNum = parseInt(lineNum);
      var moveBox = document.querySelector('.lrc-container');

      try {
        if (lineNum > 0) {
          preline = lineNum - 1;
        } else {
          preline = this.line - 1;
        }
        var newy = -(lineNum - this.scrollLines) * this.lineHeight;
        if (newy > 0) newy = 0;
        var ccLine = null;
        if (preline - 1 > 0) ccLine = document.querySelector('#song-line' + (preline - 1));
        var cLine = document.querySelector('#song-line' + preline);
        var nLine = document.querySelector('#song-line' + (lineNum + 1));
        if (ccLine) {
          ccLine.classList.remove('current-line');
        }
        if (cLine) {
          cLine.classList.remove('current-line');
        }
        if (nLine && !nohide) {
          nLine.classList.remove('current-line');
        }
        moveBox.style.transform = 'translateY(' + newy + 'px)';
      } catch (err) {
        console.log(err);
      }
    }
  }]);

  return LyricView;
}();

//module.exports = LyricView;